package com.campfire.intelligentsecurity.sys.service;

import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/ws/msgServ")
public class WebSocketServer extends BaseService {
    /**
     * 记录当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    private static enum POSITION{
        TL(1,"topLeft"), TC(2,"topCenter"), TR(3,"topRight"),
        BL(4,"bottomLeft"), BC(5,"bottomCenter"), BR(6,"bottomRight");

        private String position;
        private int id;

        POSITION(int id, String position){
            this.position = position;
            this.id = id;
        }

        public String getPosition() {
            return position;
        }

        public void setPosition(String name) {
            this.position = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }

    private static String getPosition(int pos){
        String defaultP = "topRight";
        if(pos>0&&pos<=6) {
            POSITION[] ps = POSITION.values();
            for (POSITION p: ps) {
                if(p.getId() == pos){
                    return p.getPosition();
                }
            }
        }
        return defaultP;
    }

    private static enum MSGTYPE{
        CG(1,"success", "成功消息"), WX(2,"error","危险消息"),
        JG(3,"warning","警告消息"), TZ(4,"info","通知消息");

        private String type;
        private String desc;
        private int id;

        MSGTYPE(int id, String type, String desc){
            this.type = type;
            this.desc = desc;
            this.id = id;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }

    private static String getMsgType(int pos){
        String defaultP = "info";
        if(pos>0&&pos<=4) {
            MSGTYPE[] mts = MSGTYPE.values();
            for (MSGTYPE mt: mts) {
                if(mt.getId() == pos){
                    return mt.getType();
                }
            }
        }
        return defaultP;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
        LOG.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        LOG.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        LOG.debug("服务端收到客户端[{}]的消息[{}]", session.getId(), message);
    }

    /**
     * 给前端WEB界面推送消息
     * @param msg 消息内容，必须为json,至少包含msg属性
     */
    public static void sendMessage(String msg) {
        System.out.println("推送消息：" + msg);
        for(String key : clients.keySet()){
            try {
                clients.get(key).getBasicRemote().sendText(msg);
            }catch (IOException e){
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 给前端WEB界面推送消息
     * @param msg 消息内容
     * @param title 消息标题
     * @param type 消息类型 1:success/成功消息 2:error/危险消息 3:warning/警告消息 4:info/通知消息
     * @param position 弹窗位置 1上左 2上中 3上右 4下左 5下中 6下右
     */
    public static void sendMessage(String msg, String title, int type, int position) {
        HashMap<String, Object> message = new HashMap<>();
        message.put("msg", msg);
        message.put("title", title);
        message.put("type", type);
        message.put("position", getPosition(position));
        System.out.println(JSONUtil.parse(message).toString());
        for(String key : clients.keySet()){
            try {
                clients.get(key).getBasicRemote().sendText(JSONUtil.parse(message).toString());
            }catch (IOException e){
                System.out.println(e.getMessage());
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        LOG.error("发生错误");
    }
}
